package com.chd.driversystem.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chd.driversystem.R;
import com.chd.driversystem.activity.msgbean.NetMsg;
import com.chd.driversystem.domain.User;
import com.chd.driversystem.gen.BeanServer;
import com.chd.driversystem.service.HttpService;
import com.chd.driversystem.util.network.tools.HttpConstants;
import com.chd.driversystem.util.tools.LogUtil;
import com.chd.driversystem.util.tools.MyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import lib.kingja.switchbutton.SwitchMultiButton;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "LoginActivity";


    public static final String ISJUMP = "ISJUMP";

    private static final String ISLOGGEDIN = "isloggedin";
    private static final String ISMANAGER = "ismanager";
    private static final String LOGINNAME = "loginname";
    private static final String PASSWORD = "isLoggedIn";

    private boolean isManager;

    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.btn_login)
    Button btn_login;

    @BindView(R.id.tv_signup)
    TextView tvSignup;

    @BindView(R.id.smb_switchrange)
    SwitchMultiButton smbSwitchJob;

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    private ProgressDialog LoginDailog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        pref = getPreferences(MODE_PRIVATE);
        editor = pref.edit();
        boolean isLoggedIn = pref.getBoolean(ISLOGGEDIN, false);
        isManager = pref.getBoolean(ISMANAGER, false);

        String loginname = pref.getString(LOGINNAME, "");
        String password = pref.getString(PASSWORD, "");

        if (!getIntent().getBooleanExtra(ISJUMP, false)) {
            if (isLoggedIn) {
                User user = BeanServer.getInstance()
                        .getUserByCodeAndPassword(loginname, password);
                if (user != null) {
                    MyApplication.setUser(user);
                    if (isManager) {
                        ManagerActivity.actionStart(this);
                    } else {
                        DriverActivity.actionStart(this);
                    }
                    finish();
                }
            }
        } else {
            editor.putBoolean(ISLOGGEDIN, false);
            editor.apply();
        }

        btn_login.setOnClickListener(this);
        tvSignup.setOnClickListener(this);


        smbSwitchJob.setText(Arrays.asList("司机", "管理员")).setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                Log.d(TAG, "onSwitch() called with: position = [" + position + "], tabText = [" + tabText + "]");
                switch (position) {
                    case 0:
                        isManager = false;
                        break;
                    case 1:
                        isManager = true;
                        break;
                    default:
                        break;
                }
            }
        });

        et_username.setText(loginname);
        et_password.setText(password);
        if (isManager) {
            smbSwitchJob.setSelectedTab(1);
        }else {
            smbSwitchJob.setSelectedTab(0);
        }
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(ISJUMP, true);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login:
                editor = pref.edit();
                String username = et_username.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                HttpService.startServiceLogin(this, username, password, isManager);

                LoginDailog = new ProgressDialog(LoginActivity.this);
                LoginDailog.setTitle("正在登录");
                LoginDailog.setMessage("请求中...");
                LoginDailog.setCancelable(false);
                LoginDailog.show();
                break;
            case R.id.tv_signup:
                SignUpActivity.actionStart(this);
                break;
            default:
                break;
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(NetMsg netMsg){
        if (netMsg.getType() == NetMsg.MAIN) {
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_LOGIN:
                    Log.d(TAG, "refresh() called with: netMsg = [" + netMsg + "]");
                    Toast.makeText(LoginActivity.this,
                            netMsg.getERR_MSG(),
                            Toast.LENGTH_SHORT).show();
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)){
                        if (isManager) {
                            ManagerActivity.actionStart(LoginActivity.this);
                        } else {
                            DriverActivity.actionStart(LoginActivity.this);
                        }
                        finish();
                    }
                    break;
                case HttpConstants.ACTION_SIGNUP:
                    User user = (User) netMsg.getObj();
                    Log.d(TAG, "refresh: signup:user="+user);
                    et_username.setText(user.getCode());
                    et_password.setText(user.getPassword());
                    if (user.getIsManager()){
                        isManager=true;
                        smbSwitchJob.setSelectedTab(1);
                    }else {
                        isManager=false;
                        smbSwitchJob.setSelectedTab(0);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void receiverNetMsg(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.BACKGROUND) {
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_LOGIN:
                    Log.d(TAG, "receiverNetMsg: "+netMsg);
                    LoginDailog.cancel();
                    String errMsg = "";
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        Long id = netMsg.getId();
                        if (id < 0) {
                            netMsg.setERR_MSG("数据存储失败 id为负的");
                            netMsg.setRESULT(HttpConstants.RESULT_ERR);
                        } else {
                            User user = BeanServer.getInstance().getUserById(id);
                            if (user == null) {
                                netMsg.setERR_MSG("数据存储失败 id错误");
                                netMsg.setRESULT(HttpConstants.RESULT_ERR);
                            } else {
                                MyApplication.setUser(user);
                                netMsg.setERR_MSG("登录成功");
                                editor.putBoolean(ISLOGGEDIN, true);
                                editor.putBoolean(ISMANAGER, user.getIsManager());
                                editor.putString(LOGINNAME, user.getCode());
                                editor.putString(PASSWORD, user.getPassword());
                                editor.apply();
                                isManager=user.getIsManager();
                            }
                        }
                    }
                    netMsg.setType(NetMsg.MAIN);
                    break;
                case HttpConstants.ACTION_SIGNUP:
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getId() > 0) {
                            LogUtil.d(TAG, "receiverNetMsg() id = " + netMsg.getId());
                            User user = BeanServer.getInstance().getUserById(netMsg.getId());
                            netMsg.setObj(user);
                            netMsg.setType(NetMsg.MAIN);
                        }
                    } else {
                        //提示错误信息
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
